import re

import peewee as pw

from awesomest_spider import glb


class Bilibili(glb.Model):
    title = pw.CharField(primary_key=True)
    author = pw.CharField()
    url = pw.CharField()


def main(keyword):
    result = glb.client.send_request('get', url='http://api.bilibili.com/x/web-interface/search/type', params={
        'search_type': 'video',
        'keyword': keyword,
    }).json()
    for item in result['data']['result']:
        title = re.sub(r'<em class="keyword">(.+?)</em>', r'\1', item['title'])
        data = {
            'title': title,
            'author': item['author'],
            'url': item['arcurl'],
        }
        Bilibili.replace(data).execute()
        yield data


model = Bilibili
if __name__ == '__main__':
    main(input())
